# -*- coding: utf-8 -*-
import os
import requests
import time

def getData(av):
    # av: 视频的av号

    # 通过B站api使用av号取得弹幕的cid
    if av[:2] == 'BV': 
    # https://api.bilibili.com/x/player/pagelist?bvid=BV1rz411e7UW
        result = requests.get('https://api.bilibili.com/x/player/pagelist?bvid=' + av).json()
    else:
        result = requests.get('https://api.bilibili.com/x/player/pagelist?aid=' + av + '&jsonp=jsonp').json()
    try:
        cid = result['data'][0]['cid']
    except:
        print('获取失败：获取不到av'+av+' 的视频信息')
        return '','',''

    # 构造弹幕文件路径
    commentUrl = 'https://comment.bilibili.com/' + str(cid) + '.xml'

    # suffix = str(time.time())   # 时间戳
    # suffix = 'static'           # 如果不想每次都从文件夹删除临时弹幕文件和图片，就使用这一条
    suffix = av                   # 或许...用av号当后缀能避免一些重复

    # 根据当前时间戳随机生成文件名后缀
    filename = 'comment_' + suffix + '.xml'  # 弹幕文件名
    path = os.path.join('comments/', filename)  # 存放弹幕文件的路径

    # 获得封面地址
    if av[:2] == 'BV':
        view = requests.get('https://api.bilibili.com/x/web-interface/view?bvid=' + av + '&cid=' + str(cid)).json()
    else:
        view = requests.get('https://api.bilibili.com/x/web-interface/view?aid=' + av + '&cid=' + str(cid)).json()
    pic = view['data']['pic']

    # 根据同样的时间戳生成图片文件名
    img_name = 'picture_' + suffix + os.path.splitext(pic)[1]  # 图片文件名
    img_path = os.path.join('picture/', img_name)

    # 下载弹幕
    xml = requests.get(commentUrl)
    with open(path, "wb") as file:
        file.write(xml.content)
    # 下载封面
    cover = requests.get(pic)
    with open(img_path, "wb") as file:
        file.write(cover.content)
    return path, img_path, pic